<template>
  <div style="height: 100%">
    <el-card style="height: 100%">
      <!-- 1.面包屑 -->
      <MyBread url="administrator" level1="系统管理" level2="角色管理" />
      <!-- 添加角色按钮 -->
      <el-button type="primary" plain style="margin-top: 20px;" @click="addRoleButton()">添加角色</el-button>
      <!-- 2.表格 -->
      <el-table :data="RoleList" border style="width: 100%; margin-top: 20px">
        <!-- 3.展开行 -->
        <el-table-column type="expand" width="100%">
          <template slot-scope="scoped">
            <el-row v-for="item1 in scoped.row.children" :key="item1.id">
              <el-col :span="4" style="margin-left: 100px">
                <el-tag type="success" closable @close="deleteRightTag(scoped.row, item1)">{{ item1.name }}></el-tag>
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <el-col :span="18">
                <el-tag
                  type="primary"
                  v-for="item2 in item1.children"
                  :key="item2.id"
                  closable
                  @close="deleteRightTag(scoped.row, item2)"
                  >{{ item2.name }}></el-tag
                >
              </el-col>
            </el-row>
            <!-- 无权限提示 -->
            <span
              style="margin-left: 50px"
              v-if="scoped.row.children.length === 0"
              >未分配权限</span
            >
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="authName" label="角色名称"></el-table-column>
        <el-table-column prop="authDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scoped">
            <el-button type="primary" icon="el-icon-edit" circle @click="modifyRoleInfo(scoped.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="deleteRole(scoped.row)"></el-button>
            <el-button type="success" size="medium" round plain @click="assignPermissionsButton(scoped.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 修改角色信息对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="dialogVisibleFrom"
        width="440"
        class="student_form_item">
        <el-form ref="form" :model="form" label-width="100px" :rules="rules" hide-required-asterisk>
          <el-form-item prop="authName" label="角色名称" class="student_form_item">
            <el-input v-model="form.authName" :disabled="AuthNameDisable"></el-input>
          </el-form-item>
          <el-form-item prop="authDesc" label="角色描述" class="student_form_item">
            <el-input v-model="form.authDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisibleFrom = false">取 消</el-button>
          <el-button type="primary" @click="handleAddModify()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog
        :title="titlePermissions"
        :visible.sync="dialogVisibleRightsTree"
        width="440"
        class="student_form_item">
        <el-tree
          ref="tree"
          :data="treeData"
          :props="props"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="checkedKeys">
        </el-tree>
        <div slot="footer">
          <el-button @click="cancleAssignPermissions">取 消</el-button>
          <el-button type="primary" @click="confirmAssignPermissions">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
/**
 * 后续功能：
 * 1. 不同角色分配权限
 * 2. 添加角色：跳转到后台管理页面
 * 3. 给所有组件添加 路由守卫 判断是由拥有该权限
 * 4. 注意多个权限中必须保留查看权限 给所有二级权限添加 ability 属性: GET,PUT,DELETE,POST
 * 5. 添加对应角色账户 -- 账户管理
 */
export default {
  name: "Role",
  data() {
    return {
      RoleList: [], // 角色列表
      // 所有权限列表
      RightsList: [
        {
          role: 'student',
          roleId: 0
        },
        {
          role: 'coach',
          roleId: -1
        },
        {
          role: 'administrator',
          roleId: -2
        }
      ],
      titlePermissions: "", // 分配权限标题
      dialogVisibleFrom: false, // 控制表单对话框的显隐
      isAdd: false, // 是否为添加操作
      AuthNameDisable: false,// 控制角色名称禁用
      title: "", // 添加/修改角色信息对话框标题
      form: {
        authName: "",
        authDesc: "",
        authNameEN: "administrator",
        authId: -2,
        children: []
      },
      rules: {
        authName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
        authDesc: [{ required: true, message: "角色描述不能为空", trigger: "blur" }],
      },
      dialogVisibleRightsTree: false,// 树形对话框框的显隐
      props: {
        label: 'name',
        children: 'children'
      },
      treeData: [],
      checkedKeys: [],
      CurrentRoleInfo: [], // 当前角色信息，包括权限
    }
  },
  methods: {
    // 删除标签 -- 修改权限
    deleteRightTag(row, item) {
      // 根据功能判断是否可以删除 -- 若功能是查看则不能删除
      if (item.ability === "GET") {
        this.$message.warning("该二级权限不能删除，请删除对应的一级权限")
        return
      }
      // 根据删除的 Tag 删除对应数据，更新一条数据
      row.children.forEach((element, index) => {
        // 判断删除的是否为一级权限
        if (item.level === 0) {
          // 找到要删除的 Tag标签
          if(element.id === item.id) {
            // 一级权限的删除
            row.children.splice(index, 1)
            return
          }
        } else {
          // 二级权限的删除
          element.children.forEach((ele,subindex) => {
            if (ele.id === item.id) {
              element.children.splice(subindex, 1);
              return;
            }
          });
        }
      });
      // 修改数据库，直接修改整条记录
      // this.$https.updateUserData("/role", row.id, row).then(()=>{
      //   this.$message.success(`修改${row.authName}权限成功`)
      // })
    },
    // 添加角色按钮
    addRoleButton() {
      // 修改标题
      this.title = "添加角色"
      // 修改是否为添加操作
      this.isAdd = true
      // 禁用
      this.AuthNameDisable = false
      // 显示对话框
      this.dialogVisibleFrom = true
    },
    // 添加角色
    addRole() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 判断 -- 不能添加重复角色
          const array = this.RoleList.filter(element => element.authName === this.form.authName)
          if (array.length !== 0) {
            this.$message.warning("不能添加相同角色")
            return
          }
          this.$https.addUserData("/role", this.form).then(()=>{
            this.dialogVisibleFrom = false
            this.$message.success("添加角色信息成功")
            // 表单重置
            this.form = {
              authNameEN: "administrator",
              authId: -2,
              children: []
            }
            // 重新获取角色数据
            this.$https.getRoles().then((res) => {
              this.RoleList = res.data;
            });
          })
        } else {
          this.$message.warning("表单验证不通过")
        }
      })
    },
    // 修改角色信息 -- 显示对话框
    modifyRoleInfo(row) {
      // 回滚显示信息
      this.form = row
      this.isAdd = false
      this.title = "修改角色信息"
      this.AuthNameDisable = true
      this.dialogVisibleFrom = true
    },
    // 修改角色信息 -- 修改数据库数据
    modifyRoleInfoData() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$https.updateUserData("/role", this.form.id, this.form).then(()=>{
            this.dialogVisibleFrom = false
            this.$message.success(`修改${this.form.authName}信息成功`)
            // 表单重置
            this.form = {
              authNameEN: "administrator",
              authId: -2,
              children: []
            }
          })
        } else {
          this.$message.warning("表单验证不通过")
        }
      })
    },
    // 判断是添加还是修改操作
    handleAddModify() {
      if (this.isAdd) {
        this.addRole()
      } else {
        this.modifyRoleInfoData()
      }
    },
    // 删除角色
    deleteRole(row) {
      this.$confirm('是否删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.authNameEN === "student" || row.authNameEN === "coach") {
          this.$message.warning("该角色不可删除")
          return
        }
        // 添加的角色都是 administrator，注意区分
        if (row.authName === "管理员") {
          this.$message.warning("该角色不可删除")
          return
        }
        // 进行角色的删除
        this.$https.deleteUserData("/role", row.id).then(()=>{
          this.$message.success("角色删除成功")
          // 重新获取角色信息
          this.$https.getRoles().then((res) => {
            this.RoleList = res.data;
          });
        })
      }).catch(() => {
        this.$message.info('已取消删除');          
      });
    },
    // 分配权限
    assignPermissionsButton(row) {
      this.CurrentRoleInfo = row
      this.checkedKeys = []
      if (row.children.length !== 0) {
        const array = []
        row.children.forEach(item => {
          let arr = item.children.map(ele => ele.id)
          array.push(...arr)
        })
        this.checkedKeys = array
      }
      this.RightsList.forEach(element => {
        if (row.authNameEN === element.role) {
          this.treeData = element.children
          this.titlePermissions = `分配${row.authName}权限`
          return
        }
      })
      this.dialogVisibleRightsTree = true
    },
    // 取消分配权限
    cancleAssignPermissions() {
      this.dialogVisibleRightsTree = false
    },
    // 确认分配权限
    confirmAssignPermissions() {
      const arr1 = this.$refs["tree"].getCheckedKeys()
      const arr2 = this.$refs["tree"].getHalfCheckedKeys()
      console.log(arr1);
      console.log(arr2);
      this.dialogVisibleRightsTree = false
    },
  },
  mounted() {
    // 获取角色信息
    this.$https.getRoles().then((res) => {
      this.RoleList = res.data;
    });
    // 获取并加工所有权限信息
    this.$https.getRights().then(res => {
      this.RightsList.forEach(element => {
        element.children = res.data.filter(ele => ele.pid === element.roleId)
        element.children.forEach(ele => {
          ele.children = res.data.filter(item => item.pid === ele.id)
        })
      });
    })
  },
};
</script>

<style scoped>
</style>